import { md5 } from "js-md5";
import { encrypt, decrypt } from "./encrypt";
import { Base64 } from "js-base64";
import { InternalAxiosRequestConfig } from "axios";

/**
 * 防重放CM头计算.
 * @param {*} req
 */
function setCmHeader(config) {
  let url, data, cm;
  url = "/works" + config.url;
  if (!config.headers.URL) {
    config.headers.URL = url;
  }
  if (config.data) {
    data = config.data.data;
  }
  if (data) {
    cm = md5(data + config.headers.URL);
  } else {
    cm = md5(config.headers.URL);
  }

  config.headers.CM = cm;
  config.headers.CMT = encrypt(String(new Date().getTime()), "4a765e7a03db421e85578fc7cd95ccda");
}

/**
 * 数据加密.
 * @param {*} config
 */
function encryption(config, isEncrypt) {
  if (config.data) {
    if (isEncrypt) {
      let res = encrypt(Base64.encode(JSON.stringify(config.data)), "4a765e7a03db421e85578fc7cd95ccda");
      config.data = { data: res };
    } else {
      config.data = JSON.parse(config.data);
    }
  }
}

// 白名单
const preUrl = [{ url: "/file/upload" }, { url: "/file" }, { url: "/excel/common/import" }];

// 数据加密
export const encryptData = (data: string) => {
  return encrypt(data, "4a765e7a03db421e85578fc7cd95ccda");
};

// 数据解密
export const decryptData = (data: string) => {
  return decrypt(data, "4a765e7a03db421e85578fc7cd95ccda");
};

/**
 * 安全处理.
 * @param {*} req
 */
export const secProcess = (config: InternalAxiosRequestConfig, isEncrypt: Boolean) => {
  let flag = false;

  if (preUrl.find(item => config.url?.indexOf(item.url) != -1)) {
    flag = true;
  }

  if (!flag) {
    // 参数加密
    encryption(config, isEncrypt);

    // 防重放
    setCmHeader(config);
  }
};
